package com.wushi.lenovo.asia5b.app_config;

import com.mvp.base.model.ResultModel;
import com.mvp.dagger.modules.NetworkModule;
import com.mvp.utils.JsonUtils;
import com.mvp.utils.SharedPreferencesUtils;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_model.credit.MemberBlanceModel;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/11/28.
 * 用户相关静态数据
 */
public class MemberBlanceRepository {
    private final static MemberBlanceRepository memberBalanceRepository=new MemberBlanceRepository();
    private static final String MEMBERBLANCE = "MEMBERBLANCE";

    private static synchronized MemberBlanceRepository getInstance() {
        return memberBalanceRepository;
    }

    private final ApiService apiService;
    private MemberBlanceModel memberBlanceModel;
    private Subject<MemberBlanceModel> memberBalanceSubject;
    private long lastGetMemberBalanceTime = 0;

    public MemberBlanceRepository() {
        memberBalanceSubject = PublishSubject.create();
        this.apiService = NetworkModule.getRetrofit().create(ApiService.class);;
    }

    /**
     * 从后台更新数量并通知所有界面
     */
    public static void updateMemberBalance() {
        getInstance().getMemberBalanceByNet();
    }

    public static void setMemberBalance(MemberBlanceModel memberBlanceModel) {
        getInstance().setMemberBlanceModel(memberBlanceModel);
    }

    /**
     * 订阅数据监听
     *
     * @return
     */
    public static Flowable<MemberBlanceModel> getMemberBalanceOB() {
        return getInstance().memberBalanceSubject.toFlowable(BackpressureStrategy.LATEST);
    }

    public static MemberBlanceModel getMemberBalance() {
        MemberBlanceModel memberBlanceModel = getInstance().getMemberBlanceModel();
        if (memberBlanceModel == null && UserRepository.isLogin()) {//登录但是没有财务信息?那就去获取
            updateMemberBalance();
        }
        return memberBlanceModel;
    }

    /**
     * 获取 代付款数
     */
    private void getMemberBalanceByNet() {
        if (!UserRepository.isLogin()) {
            d("--->>>>>>>>---没登录");
            return;
        }
        if ((System.currentTimeMillis() - lastGetMemberBalanceTime) < 1000) {
            return;
        }
        lastGetMemberBalanceTime = System.currentTimeMillis();
        apiService.getMemberBalance(UserInfo.getMemberId())
                .map(new Function<ResultModel<MemberBlanceModel>, MemberBlanceModel>() {
                    @Override
                    public MemberBlanceModel apply(ResultModel<MemberBlanceModel> memberBlanceModelResultModel) throws Exception {
                        return memberBlanceModelResultModel.getData();
                    }
                })
                .subscribeOn(Schedulers.io())
                .subscribe(memberBlanceModel -> {
                    //通知所有界面
                    setMemberBlanceModel(memberBlanceModel);
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }


    public MemberBlanceModel getMemberBlanceModel() {
        //先从本地拿到缓存
        if (!UserRepository.isLogin()) {
            return null;
        }
        if (memberBlanceModel == null) {
            int memberId = UserInfo.getMemberId();
            if (memberId > 0) {
                String key = MEMBERBLANCE + "+" + memberId;
                String s = (String) SharedPreferencesUtils.getData(key, "");

                try {
                    memberBlanceModel = JsonUtils.changeGsonToBean(s, MemberBlanceModel.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    memberBlanceModel = null;
                }
            }
        }
        return memberBlanceModel;
    }

    public void setMemberBlanceModel(MemberBlanceModel balanceModel) {
        memberBlanceModel = UserRepository.isLogin() ? balanceModel : null;
        saveMemberBlance(memberBlanceModel);
        if (memberBlanceModel != null) {//不能传null
            getInstance().memberBalanceSubject.onNext(memberBlanceModel);
        }
    }

    //保存用户账户信息
    private void saveMemberBlance(MemberBlanceModel model) {
        if (UserRepository.isLogin()) {
            int memberId = UserInfo.getMemberId();
            String gsonString = "";
            if (model != null) {
                gsonString = JsonUtils.createGsonString(model);
            }
            String key = MEMBERBLANCE + "+" + memberId;
            SharedPreferencesUtils.putData(key, gsonString);
        }
    }
}
